/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sfplayer.gui;

import com.apple.eawt.Application;
import com.apple.eawt.ApplicationEvent;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import sfplayer.datatypes.Broadcast;
import sfplayer.videoPlayer.VideoController;

/**
 *
 * @author micc
 */
public class WindowMain extends JFrame {
    
    // gui elements
    private Action openUrlAction, openFileAction, broadcastsAction;
    private JMenuBar mainMenuBar = new JMenuBar();		
    private JMenu fileMenu, windowMenu; 
    private Application fApplication = Application.getApplication();
    private ResourceBundle resbundle;
    private AboutBox aboutBox;
    private PrefPane prefs;
    
    // data
    private List<Broadcast> broadcasts = null;
    private VideoController videoController = null;
    private Component videoComponent = null;
    private VideoCanvas videoCanvas = null;    
    
    // videoCanvas
    private float ratio;
    private int source_width;
    private int source_height;
    private boolean mouse_down;
    private boolean mouse_resized;
    private Rectangle positRectangle;
    private int OffSetX = 0;
    private int OffSetY = 0;
    private boolean first_time = true;
    private int diffHeight;
    private int diffWidth;
    private int oldHeight;
    private int oldWidth;

    public WindowMain(List<Broadcast> broadcasts) {

        this.broadcasts = broadcasts;
        this.videoController = new VideoController();
        
        resbundle = ResourceBundle.getBundle("sfplayer/resources/windowMain", Locale.getDefault());
        
        setTitle(resbundle.getString("appName"));

        initActions();
        
        initApplication();
        
        initMenu();

        initVideoCanvas();
        
        initAspectRatio();
        
        initListeners();
        
        setVisible(true);
    }

    private void initActions() {
        
        int shortcutKeyMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
        
        openUrlAction = new OpenUrlAction( resbundle.getString("openUrlItem"), 
                KeyStroke.getKeyStroke(KeyEvent.VK_U, shortcutKeyMask) );
        
        openFileAction = new OpenFileAction( resbundle.getString("openFileItem"), 
                KeyStroke.getKeyStroke(KeyEvent.VK_O, shortcutKeyMask) );
        
        broadcastsAction = new BroadcastsAction( resbundle.getString("broadcastsItem"), 
                KeyStroke.getKeyStroke(KeyEvent.VK_B, shortcutKeyMask) );
    }
    
    private void initApplication() {
        
        fApplication.setEnabledPreferencesMenu(true);
        
        fApplication.addApplicationListener(new com.apple.eawt.ApplicationAdapter() {

            public void handleAbout(ApplicationEvent e) {
                if (aboutBox == null) {
                    aboutBox = new AboutBox();
                }
                about(e);
                e.setHandled(true);
            }

            public void handleOpenApplication(ApplicationEvent e) {
            }

            public void handleOpenFile(ApplicationEvent e) {
            }

            public void handlePreferences(ApplicationEvent e) {
                if (prefs == null) {
                    prefs = new PrefPane();
                }
                preferences(e);
            }

            public void handlePrintFile(ApplicationEvent e) {
            }

            public void handleQuit(ApplicationEvent e) {
                quit(e);
            }
        });
    } 
    
    private void initMenu() {
        
        fileMenu = new JMenu(resbundle.getString("fileMenu"));
        fileMenu.add(new JMenuItem(openFileAction));
        fileMenu.add(new JMenuItem(openUrlAction));
        mainMenuBar.add(fileMenu);

        windowMenu = new JMenu(resbundle.getString("windowMenu"));
        windowMenu.add(new JMenuItem(broadcastsAction));
        //windowMenu.addSeparator();

        mainMenuBar.add(windowMenu);

        setJMenuBar(mainMenuBar);

    }
    
    private void initVideoCanvas() {
        videoCanvas = new VideoCanvas();
        // videoCanvas.setSize(source_width, source_height);
        videoCanvas.setOpaque(true);
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(videoCanvas, "Center");
    }
    
    public void initAspectRatio() {
        // 573 x 321
        
        source_width = 640;
        source_height = 360;
        
        ratio = ((float) source_width) / ((float) source_height);
    }
    
    private void initListeners() {

        // MouseListener
        this.addMouseListener(new MouseListener() {

            public void mouseClicked(MouseEvent me) {
            }

            public void mouseEntered(MouseEvent me) {
            }

            public void mouseExited(MouseEvent me) {
            }

            public void mousePressed(MouseEvent me) {
                mouse_down = true;
            }

            public void mouseReleased(MouseEvent me) {
                if (mouse_resized = true) {
                    resizeVideo();
                    setPortPosition();
                    mouse_resized = false;
                    mouse_down = false;
                }
            }
        });

        this.addComponentListener(new ComponentAdapter() {

            public void componentHidden(ComponentEvent evt) {
            }

            public void componentMoved(ComponentEvent evt) {
                setPortPosition();
            }

            public void componentResized(ComponentEvent evt) {
                if (mouse_down == false) {
                    resizeVideo();
                    setPortPosition();
                } else {
                    mouse_resized = true;
                }
            }

            public void componentShown(ComponentEvent evt) {
                resizeVideo();
                setPortPosition();
            }
        });

        this.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent evt) {
                System.exit(0);
            }

            public void windowClosed(WindowEvent evt) {
                System.exit(0);
            }

            public void windowDeiconified(WindowEvent evt) {
                setPortPosition();
            }

            public void windowIconified(WindowEvent evt) {
            }

            public void windowActivated(WindowEvent evt) {
                setPortPosition();
            }

            public void windowDeactivated(WindowEvent evt) {
            }

            public void windowOpened(WindowEvent evt) {
                setPortPosition();
            }
        });
    }
    
    public void about(ApplicationEvent e) {
        aboutBox.setResizable(false);
        aboutBox.setVisible(true);
    }

    public void preferences(ApplicationEvent e) {
        prefs.setResizable(false);
        prefs.setVisible(true);
    }

    public void quit(ApplicationEvent e) {
        System.exit(0);
    }
    
    public void setPortPosition() {
        Point newLoc;
        positRectangle = getBounds();
        if (this.isVisible()) {
            newLoc = videoCanvas.getLocationOnScreen();
        } else {
            newLoc = new Point(0, 0);
        }
        int AbsoluteX = newLoc.x - OffSetX;
        int AbsoluteY = newLoc.y - OffSetY;
    }

    private void resizeVideo() {
        int newWidth = this.getWidth();
        int newHeight = this.getHeight();
        int vidWidth = videoCanvas.getWidth();
        int vidHeight = videoCanvas.getHeight();
        int inHeight;
        int inWidth;

        if (first_time) {
            oldHeight = newHeight;
            oldWidth = newWidth;
            diffHeight = oldHeight - vidHeight;
            diffWidth = oldWidth - vidWidth;
            oldHeight = source_height + diffHeight;
            oldWidth = source_width + diffWidth;

            newHeight = oldHeight;
            newWidth = oldWidth;

            first_time = false;
        }
        /* Check to see if we want to maintain aspect ratio.
        In this case it is permenantly YES */
        if (true) {
            if (newHeight != oldHeight || newWidth != oldWidth) {
                // Keep aspect ratio
                if (java.lang.Math.abs(oldHeight - newHeight) >=
                        java.lang.Math.abs(oldWidth - newWidth)) {
                    oldHeight = newHeight;
                    inHeight = oldHeight - diffHeight;
                    inWidth = (int) (ratio * ((float) inHeight));
                    oldWidth = inWidth + diffWidth;
                } else {
                    oldWidth = newWidth;
                    inWidth = oldWidth - diffWidth;
                    inHeight = (int) (((float) inWidth) / ratio);
                    oldHeight = inHeight + diffHeight;
                }
            }
            this.setSize(oldWidth, oldHeight);
        } else {
            oldHeight = newHeight;
            oldWidth = newWidth;
        }
    /*fvmain.SetSize( fvnumber,
    this.videoCanvas.getWidth(),this.videoCanvas.getHe ight() );*/
    }

    public void openUrl(String url) {

        videoController.openUrl(url);

        if (videoComponent != null) {
            this.getContentPane().remove(videoComponent);
        }
        videoComponent = videoController.getVideoComponent();

        this.getContentPane().add(videoComponent, "Center");
        
        this.setSize(640,480);
    }

    public void openFile() {

        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showOpenDialog(null);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            String file = "file://" + chooser.getSelectedFile().getAbsolutePath();
            videoController.openFile(file);
        }

    }

    private void showDialogBroadcast() {
        Broadcasts dialog = new Broadcasts(this, broadcasts);
        dialog.setPreferredSize(new Dimension(200, 200));
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setAlwaysOnTop(true);
        dialog.setVisible(true);
    }


    public class OpenUrlAction extends AbstractAction {

        public OpenUrlAction(String text, KeyStroke shortcut) {
            super(text);
            putValue(ACCELERATOR_KEY, shortcut);
        }

        public void actionPerformed(ActionEvent e) {
            String url = "mms://schweizer-8.wmod.llnwd.net/a1480/e1/vod/glanzundgloria/2008/10/glanzundgloria_20081015_184531_1500k.wmv";
                url = javax.swing.JOptionPane.showInputDialog(this, url);
                openUrl(url);
        }
    }

    public class OpenFileAction extends AbstractAction {

        public OpenFileAction(String text, KeyStroke shortcut) {
            super(text);
            putValue(ACCELERATOR_KEY, shortcut);
        }

        public void actionPerformed(ActionEvent e) {
            openFile();
        }
    }

    public class BroadcastsAction extends AbstractAction {

        public BroadcastsAction(String text, KeyStroke shortcut) {
            super(text);
            putValue(ACCELERATOR_KEY, shortcut);
        }

        public void actionPerformed(ActionEvent e) {
            showDialogBroadcast();
        }
    }

}
